from flask import Blueprint, jsonify, request
from db import db1
from utils.redisconn import r
import json
import datetime
from utils.comm import get_data

bp_work = Blueprint('workf', __name__)


@bp_work.route('/workflow')
def workflow():
    sql = "select * from workf"
    res = db1.find_all(sql)
    return jsonify({'code': 200, 'list': res})


# 获取数据源接口
@bp_work.route('/getresourcedata')
def getresourcedata():
    # 从redis取，如果有直接返回
    values = r.get_str('dataresouce')
    if values:
        list = eval(values)
    else:
        # 如果没有查询
        sql = "select * from data_source"
        res = db1.find_all(sql)
        list = []
        if res:
            for i in res:
                dict = {'id': i['id'], 'name': i['name']}
                sql1 = "select id,name,type from %s" % (i['tablename'])
                subres = db1.find_all(sql1)
                dict['mes'] = subres
                list.append(dict)
        # 存入redis
        r.set_str('dataresouce', json.dumps(list))
    return jsonify({"code": 200, 'list': list})


@bp_work.route('/updateworkf', methods=['POST', 'GET'])
def updateworkf():
    if request.method == 'POST':
        res = request.json
        sql = "update workf set params='%s' where id=%d" % (res['params'], int(res['id']))
        db1.update(sql)
        return jsonify({"code": 200, 'msg': '成功'})
    else:
        pid = request.args.get('id')
        sql = "select * from workf where id=%d" % int(pid)
        res = db1.find(sql)
        return jsonify({'code': 200, 'list': res})


# [{"lable":"姓名","type":"input","values":"[{"id":1,"name":"事假","type":1},{"id":2,"name":"产假","type":2},{"id":3,"name":"病假","type":3}]"},{"lable":"工号","type":"input"}]

# 审批
@bp_work.route('/examine', methods=['POST'])
def examine():
    data = request.json
    data1 = data['approver'][0]
    print(data1)
    sql1 = "insert into examine (title,params,stutas,approver,next_approver,userid,workfid) values ('%s','%s',1,'%s',%d,%d,%d)" \
           % (data['title'], data['params'], json.dumps(data['approver']), int(data1), int(data['userid']),
              int(data['workfid']))
    db1.update(sql1)
    sql1 = "select id,title from examine where title='%s'" % (data['title'])
    task = db1.find(sql1)
    # 把当前任务加到redis中，选用hash类型
    key = 'task%d' % (data1)
    r.insert_hash_set(key, task['id'], task['title'])
    return jsonify({'code': 200, 'msg': '提交成功'})


def getdeptdata(data):
    tree = {}
    list = []
    for i in data:
        tree[i['id']] = i

    for j in data:
        pid = j['pid']
        if not pid:
            j['type'] = 1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children'] = []
            # 查询此部门下所有员工
            sql = "select * from users where dept_id=%d " % (int(j['id']))
            res = db1.find_all(sql)
            userlist = []
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type'] = 2
            tree[pid]['children'].append(j)

    return list


@bp_work.route('/getcomanyuser')
def getcomanyuser():
    # 获取所有公司及所有部门
    sql = "select * from dept"
    res = db1.find_all(sql)
    mes = getdeptdata(res)
    return jsonify({'code': 200, 'list': mes})
    # 数据重组，查询员工


# 待我审批
@bp_work.route('/mytaskaudit')
def mytaskaudit():
    id = request.args.get('id')
    # 从redis中获取我的任务列表
    key = 'task%d' % (int(id))
    # print(key)
    task = r.get_all_hash_params(key)
    list = []
    for k, v in task.items():
        uid = str(k, encoding='utf8')
        title = str(v, encoding='utf8')
        list.append({'id': uid, 'title': title})

    return jsonify({"code": 200, 'list': list})


@bp_work.route('/examineone')
def examineone():
    eid = request.args.get('eid')
    sql = "select * from examine where id=%d" % int(eid)
    res = db1.find(sql)
    res['params'] = json.loads(res['params'])
    res['approver'] = json.loads(res['approver'])
    sql1 = "select * from audit_record where eid=%d" % int(eid)
    res1 = db1.find(sql1)
    res['audit_record'] = res1
    return jsonify({'code': 200, 'list': res})


# @bp_work.route('/dispose',methods=['POST'])
# def dispose():
#     data = request.json
#     sql = "select * from examine where id=%d"%int(data['eid'])
#     res = db1.find(sql)
#     lis = json.loads(res['approver'])
#     sql1 = "update examine set stutas=2,next_approver=%d where id=%d"%(lis[2],int(data['eid']))
#     db1.update(sql1)
#     # 把当前任务加到redis中，选用hash类型
#     key = 'task%d' % (lis[1])
#     r.insert_hash_set(key, res['id'], res['title'])
#     return jsonify({'code': 200, 'msg': '提交成功'})


@bp_work.route('/taskrecordM', methods=['POST'])
def taskrecordM():
    data = request.json
    # 写审批记录表
    time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
    try:
        sql = "insert into audit_record(eid,userid,username,is_agree,reason,add_time) values(%d,%d,'%s',%d,'%s','%s')" % (
            int(data['eid']), int(data['userid']), data['username'], int(data['radio']), data['text'], time)
        db1.add(sql)
    except:
        return jsonify({"code": 10010, 'mes': '审批失败'})

    # 判断是否同意
    tsql = "select * from examine where id=%d" % (int(data['eid']))
    task = db1.find(tsql)
    key = 'task%d' % (int(data['userid']))
    # 清除当前redis中的信息
    r.del_hash_params(key, int(data['eid']))
    auditlist = json.loads(task['approver'])
    # 是不是最后一个审批人
    index = auditlist.index(int(data['userid']))
    if data['radio'] == '1':
        try:
            # 同意，查询任务，更新下一审批人，redis清除当前审批人，加入下一审批人，
            # 任务表中更新任务状态，如果是最后一个审批人，查新成已经完成，其它审核中
            if index == len(auditlist) - 1:
                sql1 = "update examine set stutas=3,next_approver=0 where id=%d" % (int(data['eid']))
                db1.add(sql1)
            else:
                sql1 = "update examine set stutas=2,next_approver=%d where id=%d" % (
                    auditlist[index + 1], int(data['eid']))
                db1.add(sql1)
                # 添加redis
                newkey = 'task%d' % (int(auditlist[index + 1]))
                # 把下一审批人加入到redis
                r.insert_hash_set(newkey, int(data['eid']), task['title'])
            db1.commit()
        except:
            db1.rollback()
            return jsonify({"code": 10020, 'mes': '失败'})
    else:
        # 不同意，把redis中当前审批人清除，任务表中的下一审批人清空
        if index == 0:
            sql1 = "update examine set stutas=1,next_approver=0 where id=%d" % (int(data['eid']))
            db1.update(sql1)
        else:
            sql1 = "update examine set next_approver=%d where id=%d" % (int(auditlist[index - 1]), int(data['eid']))
            db1.update(sql1)
            # 添加redis
            newkey = 'task%d' % (int(auditlist[index - 1]))
            # 把下一审批人加入到redis
            r.insert_hash_set(newkey, int(data['eid']), task['title'])
    return jsonify({"code": 200})


@bp_work.route('/examineonelist')
def examineonelist():
    userid = request.args.get('userid')
    sql = "select * from examine where userid=%d" % int(userid)
    res = db1.find_all(sql)
    for i in res:
        i['params'] = json.loads(i['params'])
        i['approver'] = json.loads(i['approver'])
    return jsonify({'code': 200, 'list': res})


@bp_work.route('/examineoneM')
def examineoneM():
    eid = request.args.get('eid')
    sql = "select * from examine where id=%d" % int(eid)
    res = db1.find(sql)
    res['params'] = json.loads(res['params'])
    res['approver'] = json.loads(res['approver'])
    return jsonify({'code': 200, 'list': res})


@bp_work.route('/userlist')
def userlist():
    sql = "select * from users"
    res = db1.find_all(sql)
    return jsonify({'code': 200, 'list': res})


@bp_work.route('/messageinsert', methods=['POST'])
def messageinsert():
    data = request.json
    userlist = json.loads(data['userlist'])
    sql = "insert into message (title,content,type,starttime,outtime,rank) values ('%s','%s','%s','%s','%s','%s')" % \
          (data['title'], data['text'], data['type'], data['starttime'], data['outtime'], data['rank'])
    db1.update(sql)
    sql2 = "select id from message where title='%s'" % data['title']
    res2 = db1.find(sql2)
    for i in userlist:
        sql1 = "insert into user_msg (msgid,userid) values (%d,%d)" % (int(res2['id']), int(i))
        db1.update(sql1)
    return jsonify({'code': 200})


# @bp_work.route('/messageinsert', methods=['POST'])
# def messageinsert():
#     data = request.json
#     sql = "insert into xiaoxi(title,xiaoxi_type,content,status,type,level,ctime) values ('%s','%s',%d,'%s',%d,'%s',%d) " \
#           % (data['title'], data['xiaoxi_type'], int(data['content']), data['status'], int(data['type']), data['level'],
#              int(data['ctime']))
#     res2 = db1.update(sql)
#     if int(data['ctime']) == 1:
#         for i in data['userlist']:
#             sql1 = "insert into user_msg (xiaoxi_id,user_id) values (%d,%d)" % (int(res2), int(i))
#             db1.update(sql1)
#     else:
#         pass
#         # key = 'msg'+ str(res2)
#         # r.insert_set(key,data['userid'])
#
#     return jsonify({'code': 200})


# @bp_work.route('/notice', methods=['GET', 'POST'])
# def getmessage():
#     if request.method == 'GET':
#         userid = request.args.get('userid')
#         sql = "select xiaoxi.id,xiaoxi.title,xiaoxi.xiaoxi_type,user_xiaoxi.status from xiaoxi" \
#               " left join user_xiaoxi on xiaoxi.id=user_xiaoxi.xiaoxi_id where user_id=%d or xiaoxi.xiaoxi_type=2" % int(
#             userid)
#         res = db1.find_all(sql)
#         for i in res:
#             if i['status'] == None:
#                 key = 'xiaoxi' + str(i['id'])
#                 data = r.find_set(key)
#                 if data:
#                     i['status'] = 1
#                 else:
#                     i['status'] = 2
#         return jsonify({'code': 200, 'list': res})
#     else:
#         data = request.json
#         if int(data['type']) == 1:
#             sql = "update user_xiaoxi set status=1 where user_id=%d and xiao_id=%d" % (
#                 int(data['user_id']), int(data['xiaoxi_id']))
#             db1.update(sql)
#         if int(data['type']) == 2:
#             key = 'xiaoxi' + str(data['xiaoxi_id'])
#             r.insert_set(key, str(data['user_id']))
#         return jsonify({'code': 200})


@bp_work.route('/customer')
def customer():
    sql = "select * from customer"
    res = db1.find_all(sql)
    return jsonify({'code': 200, 'list': res})


@bp_work.route('/post_cus', methods=['POST'])
def post_cus():
    data = get_data()
    sql = "insert into customer(name,money,company_name,manger_id,refromid) values ('%s',%d,'%s','%s','%s')" \
          % (data['name'], int(data['money']), data['company_name'], data['manger_id'], data['refromid'])
    res = db1.update(sql)
    return jsonify({'code': 200, 'list': res})


@bp_work.route('/get_customer_manager')
def get_customer_manager():
    sql = "select * from customer_manager"
    res = db1.find_all(sql)
    return jsonify({'code': 200, 'list': res})


@bp_work.route('/get_refromid')
def get_refromid():
    sql = "select * from reg_form"
    res = db1.find_all(sql)
    return jsonify({'code': 200, 'list': res})
